package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-master/cache"
	"novel-master/models"
	"novel-master/pkg"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "redis_key_" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误3次",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误三次,封禁两个小时",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
	})
	return
}

func UserList(c *gin.Context) {
	var books []models.Book

	redis_key := "redis_book"
	CacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if CacheData == "" {
		models.DB.Find(&books)
		JsonData, _ := json.Marshal(books)
		cache.Rdb.Set(cache.Ctx, redis_key, JsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(CacheData), &books)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": books,
	})
	return
}

func UserXq(c *gin.Context) {
	var book models.Book
	id := c.Query("id")
	models.DB.Where("id = ?", id).First(&book)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": book,
	})
	return
}
